package com.agileai.em.module.evection.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.AppConfig;
import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.em.common.ProcessHelper;
import com.agileai.em.cxmodule.BizCodeUtil;
import com.agileai.em.module.evection.service.EmEvectionManage;
import com.agileai.em.wsproxy.BizAttribute;
import com.agileai.em.wsproxy.DraftWorkItem;
import com.agileai.em.wsproxy.LaunchWorkItem;
import com.agileai.em.wsproxy.ProcessService;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.bizmoduler.core.MasterSubService;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.controller.core.MasterSubEditMainHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;

public class EmEvectionManageEditHandler
        extends MasterSubEditMainHandler {
	private static final String PROCESS_CODE = "Emevection";
    public EmEvectionManageEditHandler() {
        super();
        this.listHandlerClass = EmEvectionManageListHandler.class;
        this.serviceId = buildServiceId(EmEvectionManage.class);
        this.baseTablePK = "EVE_ID";
        this.defaultTabId = "_base";
    }
    public ViewRenderer prepareDisplay(DataParam param) {
		String operaType = param.get(OperaType.KEY);
		String currentSubTableId = param.get("currentSubTableId",defaultTabId);
		setAttribute("showCode", true);
		if(OperaType.CREATE.equals(operaType)){
		User user = (User) this.getUser();
		setAttribute("EVE_APPLICATION", user.getUserId());
		setAttribute("EVE_APPLICATION_NAME", user.getUserName());
		setAttribute("EVE_REIMBURSEMENT_TIME",new Date());
		setAttribute("EVE_SUBSIDY", "0.00");
		setAttribute("EVE_TOTAL_MONEY", "0.00");
		setAttribute("showEdit", true);
		String invokeFrom = param.get("invokeFrom");
		setAttribute("invokeFrom", invokeFrom);
		setAttribute("showCode", false);
		}
		if (currentSubTableId.equals(MasterSubService.BASE_TABLE_ID)){
			if (isReqRecordOperaType(operaType)){
				String bizId = param.getString("BizId");
				if(StringUtil.isNotNullNotEmpty(bizId)){
					param.put("EVE_ID",param.getString("BizId"));
				}
				DataRow record = getService().getMasterRecord(param);
				List<DataRow> records = getService().findApproveOpinionRecords(param);
				if(records.size()==0){
					setAttribute("hasAppRecords", false);
				}else{
					setAttribute("hasAppRecords", true);
					setAttribute("ApproceOpinionRecords", records);
				}
				setAttribute("showFlow", true);
				if("UNSUBMITTED".equals(record.getString("EVE_STATE"))){
					setAttribute("showEdit", true);
					setAttribute("showSubmit", true);
					setAttribute("showFlow", false);
				}
				setAttributes(param);
				this.setAttributes(record);	
			}
		}else{
			List<DataRow> subRecords = getService().findSubRecords(currentSubTableId, param);
			this.setAttribute(currentSubTableId+"Records", subRecords);
			this.setAttribute("EVE_ID",param.getString("EVE_ID"));
			if("UNSUBMITTED".equals(param.getString("EVE_STATE"))){
				this.setAttribute("showEdit", true);
			}
			this.setAttribute("EVE_STATE", param.getString("EVE_STATE"));
		}
		String invokeFrom = param.get("invokeFrom");
		setAttribute("invokeFrom", invokeFrom);
		this.setAttribute("currentSubTableId", currentSubTableId);
		this.setAttribute("currentSubTableIndex", getTabIndex(currentSubTableId));
		String operateType = param.get(OperaType.KEY);
		this.setOperaType(operateType);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
    
    protected void processPageAttributes(DataParam param) {
        setAttribute("EVE_STATE",FormSelectFactory.create("EM_STATE")
        		.addSelectedValue(getOperaAttributeValue("EVE_STATE","UNSUBMITTED")));
        initMappingItem("EVP_TRANSPORTATION_WAY",
                FormSelectFactory.create("TRANSPORTATION_WAY").getContent());
    }

    protected String[] getEntryEditFields(String currentSubTableId) {
        List<String> temp = new ArrayList<String>();
        return temp.toArray(new String[] {  });
    }
    @PageAction
    public ViewRenderer saveMasterRecord(DataParam param)throws Exception{
		String operateType = param.get(OperaType.KEY);
		String responseText = "fail";
		User user = (User) this.getUser();
		if (OperaType.CREATE.equals(operateType)){
			param.put("sdate",DateUtil.getDateByType(DateUtil.YYMMDD_SLANTING, new Date())+" 00:00:00");
			param.put("edate",DateUtil.getDateByType(DateUtil.YYMMDD_SLANTING, new Date())+" 23:59:59");
			List<DataRow> list = this.getService().findMasterRecords(param);
			String bizCode = BizCodeUtil.create("EVE", list, BizCodeUtil.withPrefix);
			param.put("EVE_CODE",bizCode);
			getService().createMasterRecord(param);
			ProcessHelper processHelper = ProcessHelper.instance();
	   		ProcessService processService = processHelper.getBPMService();
	   		String title = param.get("PC_NAME")+"_"+param.get("EVE_APPLICATION_NAME");
	   		String uuId = param.get("EVE_ID");
	   		
	   		DraftWorkItem draftWorkItem = new DraftWorkItem();
	   		draftWorkItem.setProcessCode(PROCESS_CODE);
	   		draftWorkItem.setUserCode(user.getUserCode());
	   		draftWorkItem.setBizTitle(title);
	   		draftWorkItem.setBizRecordId(uuId);
	   		draftWorkItem.setBizRecordCode(param.getString("EVE_CODE"));
	   		processService.saveDraft(draftWorkItem);
			responseText = param.get(baseTablePK);
		}
		else if(OperaType.UPDATE.equals(operateType)){
			getService().updateMasterRecord(param);
			saveSubRecords(param);
			responseText = param.get(baseTablePK);
		}
		String masterRecordId = param.get("EVE_ID");
		this.getService().computeTotalMoney(masterRecordId);
		return new AjaxRenderer(responseText);
	}
    
    protected String getEntryEditTablePK(String currentSubTableId) {
        HashMap<String, String> primaryKeys = new HashMap<String, String>();
        primaryKeys.put("EmExpenses", "EXP_ID");
        return primaryKeys.get(currentSubTableId);
    }

    protected String getEntryEditForeignKey(String currentSubTableId) {
        HashMap<String, String> foreignKeys = new HashMap<String, String>();
        foreignKeys.put("EmExpenses", "EVE_ID");
        return foreignKeys.get(currentSubTableId);
    }
    
    @PageAction
	public ViewRenderer submit(DataParam param) throws Exception {
    	String responseText = FAIL;
		try {
			List<DataRow> subRecords = getService().findSubRecords("EmExpenses", param);
			if(subRecords.size()<1){
				responseText = "nosub";
			}else{
				User user = (User)getUser();
				param.put("EVE_STATE", "AUDITING");
				getService().updateMasterRecord(param);
				ProcessHelper processHelper = ProcessHelper.instance();
				ProcessService processService = processHelper.getBPMService();
				List<BizAttribute> attributeList = new ArrayList<BizAttribute>();
				BizAttribute bizAttribute = new BizAttribute();
				bizAttribute.setCode("userId");
				bizAttribute.setValue(user.getUserId());
				attributeList.add(bizAttribute);
				String bizRecordId = param.get("EVE_ID");
				String bizRecordCode = param.get("EVE_CODE");
				if(StringUtil.isNullOrEmpty(bizRecordId)){
					bizRecordId = KeyGenerator.instance().genKey();
				}
				String processId = processService.getCurrentProcessId(PROCESS_CODE);
				String title = param.get("PC_NAME")+"_"+param.get("EVE_APPLICATION_NAME");
				LaunchWorkItem launchWorkItem = processHelper.createLaunchWorkItem(processId);
				launchWorkItem.getAttributeList().addAll(attributeList);
				launchWorkItem.setTitle(title);
				launchWorkItem.setBizRecordId(bizRecordId);
				launchWorkItem.setBizRecordCode(bizRecordCode);
				launchWorkItem.setUserCode(user.getUserCode());		
				param.put("SKIP_FIRST_NODE", "true");
				boolean skipFirstNode = "true".equals(param.get("SKIP_FIRST_NODE"));
				processService.launchProcess(launchWorkItem,skipFirstNode);
				responseText = SUCCESS;
			}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
    @PageAction
  	public ViewRenderer retrieveIds(DataParam param) throws JSONException{
  		String responseText = "";
  		AppConfig appConfig = BeanFactory.instance().getAppConfig();
 		String BpmShowFlowUrl = appConfig.getConfig("GlobalConfig", "BpmShowFlowUrl");
 		setAttribute("BpmShowFlowUrl", BpmShowFlowUrl);
  		ProcessHelper processHelper = ProcessHelper.instance();
  		ProcessService bpmService = processHelper.getBPMService();
  		String bizRecordId = param.getString("EVE_ID");
  		List<String> aa = bpmService.getProcessId8InstId(PROCESS_CODE, bizRecordId);
  		JSONObject jsonObject = new JSONObject();  
          jsonObject.put("processId", aa.get(0));
          jsonObject.put("processInstId", aa.get(1));
          jsonObject.put("BpmShowFlowUrl", BpmShowFlowUrl);
          String json = jsonObject.toString();
  		responseText=json;
  		return new AjaxRenderer(responseText);
  	}
    protected EmEvectionManage getService() {
        return (EmEvectionManage) this.lookupService(this.getServiceId());
    }
}
